package handler

import (
	"compress/common"
	"sync"

	"compress/location"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strconv"
)

func GetImgByPath(w http.ResponseWriter, r *http.Request) {
	query := r.URL.Query()
	path := query["path"][0]
	if  path == "" {
		w.Write(common.ErrJson(20,"不存在",path))
		return
	}

	if !location.IsImgFile(path) {
		w.Write(common.ErrJson(15,"不是图片文件",path))
	}
	fmt.Println("显示图片:"+path)
	b,err := ioutil.ReadFile(path)
	if err != nil {
		w.Write(common.ErrJson(20,err.Error(),path))
		return
	}




	w.Write(b)
}



type Sender struct {
	message M
	mt int
	data []map[string]interface{}
}

func (s *Sender) sendData(n int)  {
	var mux sync.Mutex
	mux.Lock()
	if len(s.data) >= n {
		s.message.AddMsgQueue(s.mt,common.WsRes{
			Code:      common.SUCCESS,
			Data:      s.data[:n],
			ErrorCode: 0,
			Action:    s.message.Action,
			Msg   : "OK",
		});
		s.data = s.data[n:]
	}
	defer mux.Unlock()
}

//发送本地图信息给客户端，每次10条直到发完
func GetLocationImgs(mt int,message M){
	p := message.Data["path"]
	path := common.Strval(p)
	fmt.Println(path)

	if !location.IsDir(path) {
		message.AddMsgQueue(mt,common.WsRes{
			Code:      common.ERROR,
			Data:      nil,
			ErrorCode: 229,
			Action:    message.Action,
			Msg   : "目录:"+path+"不为目录或者不存在",
		})
		return;
	}//end if isDir
	fileInfo,err := ioutil.ReadDir(path)
	fmt.Println("读了",path)
	if err!= nil {
		message.AddMsgQueue(mt,common.WsRes{
			Code:      common.ERROR,
			Data:      nil,
			ErrorCode: 236,
			Action:    message.Action,
			Msg   : "OK",
		});
		return
	}//end if err


	sender := Sender{
		message: message,
		mt: mt,
		data: []map[string]interface{}{},
	}

	num := 1
	for _, info := range fileInfo {
		name := info.Name()
		file := path+"\\"+name
		if !location.IsImgFile(file) {
			continue;
		}
		go func() {
			num = common.Random(1,10)
		}()
		size := make(chan int64)
		md5  := make(chan string)
		go func(file string) {
			size<- location.GetSize(file)
		}(file)
		go func(file string) {
			md5<- location.Md5(file)
		}(file)


		//fmt.Println(mp)
		sender.data = append(sender.data,map[string]interface{}{
			"name" : file,
			"size" : <-size,
			"md5"  : <-md5,
		});
		//fmt.Println(len(res),file)
		sender.sendData(num)
	}//end for
	sender.sendData(1)
}//end GetLocationImgs()




func CompressImgs(mt int, mess []byte, message M) {
	type Da struct {
		Output string `json:"output,omitempty"`
		CompressImgs []map[string]string `json:"compress_imgs,omitempty"`
	}
	type Msg struct {
		Action string      `json:"action,omitempty"`
		Data   Da          `json:"data,omitempty"`
	}
	msg := Msg{}
	err := json.Unmarshal(mess,&msg)
	if err != nil {
		fmt.Println(err)

		AddMsgQueue(mt,common.WsRes{
			Code:      common.ERROR,
			Data:      nil,
			ErrorCode: 0,
			Action:    msg.Action,
			Msg : "压缩传来的数据有误:"+err.Error(),
		});
		return;
	}

	num := 1

	sender := Sender{
		message: message,
		mt: mt,
		data: []map[string]interface{}{},
	}

	for k, v := range msg.Data.CompressImgs {
		go func() {
			num = common.Random(1,10)
		}()
		fmt.Println(k,v)
		img := v["img"]
		q,err := strconv.Atoi(v["q"])
		if err != nil {
			q = 100
		}

		size := make(chan int64)
		md5  := make(chan string)
		go func(file string) {
			size<- location.GetSize(file)
		}(img)
		go func(file string) {
			md5<- location.Md5(file)
		}(img)


		res_img,err := location.Compress(img,q,msg.Data.Output)

		if err != nil {
			fmt.Println(err)
			return;
		}

		sender.data = append(sender.data,map[string]interface{}{
			"source_md5" : <-md5,//原图MD5
			"img" : img,
			"res_img" : res_img,
			"res_size" : <-size,
		})
		sender.sendData(num)


	}//end for

	sender.sendData(1)
}//end func CompressImgs()


